package com.lzj.demo.service.impl;

import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.lzj.demo.common.ResponseObject;
import com.lzj.demo.dto.Order;
import com.lzj.demo.mapper.Order2Mapper;
import com.lzj.demo.service.AccountService;
import com.lzj.demo.service.OrderService;
import com.lzj.demo.service.StorageService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;

/**
 * (Order)表服务实现类
 *
 * @author makejava
 * @since 2023-02-09 09:51:40
 */
@Slf4j
@Service
public class OrderServiceImpl extends ServiceImpl<Order2Mapper, Order> implements OrderService {
    @Resource
    private AccountService accountService;
    @Resource
    private StorageService storageService;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public ResponseObject createOrder(Order order) {
        log.info("------->下单开始");
        //本应用创建订单
        this.save(order);
        log.info("------->订单已创建");

        //扣减库存
        log.info("------->order-service中扣减库存开始");
        storageService.decrease(order.getProductId(),order.getCount());
        log.info("------->order-service中扣减库存结束");

        //扣减余额
        log.info("------->order-service中扣减余额开始");
        accountService.decrease(order.getUserId(),order.getMoney());
        log.info("------->order-service中扣减余额结束");

        //模拟异常,本地事务回滚
        int a = 1/0;

        //修改订单状态为已完成结
        log.info("------->order-service中修改订单状态开始");
        updateOrder(order);
        log.info("------->order-service中修改订单状态结束");

        log.info("------->下单结束");
        return ResponseObject.ok("订单创建成功!");
    }

    /**
     * 修改订单状态为已完成
     * */
    public void updateOrder(Order order){
        LambdaUpdateWrapper<Order> wrapper = Wrappers.lambdaUpdate(Order.class);
        wrapper.set(Order::getStatus,1)
                .eq(Order::getId,order.getId());
        this.update(wrapper);
    }
}

